﻿using System;
using System.Data;
using FineUI;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Center;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Org;
using ZHDJ.PersonalCenter.BLL;
using ZHDJ.WebPage;
using System.Linq;
using DropDownList = System.Web.UI.WebControls.DropDownList;

namespace ZHDJ.PersonalCenter.Module.RelationshipTransfer
{
    public partial class RelationshipTransferApproval : PageBase
    {
        public string TaskID
        {
            get
            {
                return Request.QueryString["TaskID"] ?? "";
            }
        }

        public string RelationID
        {
            get
            {
                return Request.QueryString["RelationID"] ?? "";
            }
        }

        public string EndSign
        {
            get
            {
                return Request.QueryString["end"] ?? "";
            }
        }

        public DataTable ProcessInfo
        {
            get
            {
                return PartyRelationshipTransfer.GetProcessesApproval(this.RelationID);
            }
        }

        public PartyRelationshipTransfer TransferModel
        {
            get;
            set;
        }

        public PartyOrgMember OrgMemberModel
        {
            get;
            set;
        }
        /// <summary>
        /// 介绍信发出单位
        /// </summary>

        public string LetterFrom { get; set; }
        /// <summary>
        /// 介绍信接收单位
        /// </summary>
        public string LetterTo { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {

            loadInfo();
            string taskType = PartyTask.GetTaskTypeByTakeID(this.TaskID);

            if (taskType != "2") return;

            txtExplain.Visible = false;
            lblExplain.Visible = false;
            btnCancel.Visible = false;
            //结束标志
            btnArgee.Visible = false;
            btnNotArgee.Visible = false;
            PartyTaskHelper.TaskDoneByTaskId(this.TaskID, this.CurrentUser.LoginID);
            btnCancel.Text = "关闭";

            
        }

        public void loadInfo()
        {
            TransferModel = DB.PartyRelationshipTransfers.Find(this.RelationID);
            OrgMemberModel = DB.PartyOrgMembers.Find(TransferModel.Applicant);
            if (TransferModel.Status != "审批中" && TransferModel.Status != "不同意转组织")
            {
                //btnArgee.Visible = false;
                //btnNotArgee.Visible = false;
                PartyTaskHelper.TaskDoneByTaskId(this.TaskID, this.CurrentUser.LoginID);
            }
            if (Convert.ToString(TransferModel.SerialNumber) != "")
            {
                this.txtOrderNo.Text = TransferModel.SerialNumber;
            }

            this.txtValidTime.Text = TransferModel.ValidTime.ToString();

            //
            var branchID = this.CurrentUser.BranchID;

            var targetbranchs = DB.PartyRelationshipTageBranchs.Where(o => o.ApplyID == TransferModel.ID).ToList();


            var current = targetbranchs.Find(o => o.TageBranchID == branchID);
            if (current.OrderNo == current.SumOrder)
            {
                LetterFrom = targetbranchs.Find(o => o.OrderNo == current.OrderNo - 1).TageBranchID;
                LetterTo = current.TageBranchID;
            }
            else {
                LetterFrom = current.TageBranchID;
                LetterTo = targetbranchs.Find(o => o.OrderNo == current.OrderNo + 1).TageBranchID;
            }

            if (LetterFrom == "D658070EC3BF425BA8417745FDCBFCB0" && TransferModel.Type==2) {
                LetterFrom = "e9fe4f820dff11e6b98252540003aec6";
            }

            if (LetterTo == "D658070EC3BF425BA8417745FDCBFCB0" && TransferModel.Type == 1) {
                LetterTo = "e9fe4f820dff11e6b98252540003aec6";
            }

            if (TransferModel.Type == 1 && current.OrderNo == current.SumOrder)
            {
                LetterFrom = "e9fe4f820dff11e6b98252540003aec6";
                LetterTo = TransferModel.TageBranchID;
            }


            //if (branchID == TransferModel.FormerBranchID)//如果当前单位为发出单位则发出为本单位，接收为本单位上级党委
            //{
            //    LetterFrom = branchID;
            //    LetterTo = DB.PartyOrgBranchs.Find(branchID).ParentBranchID;
            //}
            //else if (branchID == TransferModel.TageBranchID)
            //{
            //    LetterTo = branchID;
            //    var parentToBranchId = DB.PartyOrgBranchs.Find(TransferModel.TageBranchID).ParentBranchID;
            //    if (parentToBranchId == "D658070EC3BF425BA8417745FDCBFCB0")//
            //    {
            //        LetterFrom = DB.PartyOrgBranchs.Find(TransferModel.FormerBranchID).ParentBranchID;
            //    }
            //    else
            //    {
            //        LetterFrom = parentToBranchId;
            //    }
            //}
            //else//如果当前单位不是发出支部，则发出单位为发出支部的上级党委；接收单位为接收支部的上级党委
            //{
            //    var parentFrom = DB.PartyOrgBranchs.Find(TransferModel.FormerBranchID).ParentBranchID;
            //    if (branchID == parentFrom)
            //    {
            //        LetterFrom = branchID;

            //        var toparentid = DB.PartyOrgBranchs.Find(TransferModel.TageBranchID).ParentBranchID;
            //        if (branchID == toparentid)//党委内部转移
            //        {
            //            LetterTo = TransferModel.TageBranchID;
            //        }
            //        else
            //        {
            //            LetterTo = toparentid;
            //        }

            //    }
            //    else
            //    {
            //        LetterFrom = branchID;
            //        LetterTo = TransferModel.TageBranchID;
            //    }
            //}
        }

        protected void btnArgee_Click(object sender, EventArgs e)
        {
            //loadInfo();

            string branchID = PartyTask.GetTaskToUser(this.TaskID);
            var loginid = this.CurrentUser.LoginID;
            TransferModel = DB.PartyRelationshipTransfers.Find(this.RelationID);
            TransferModel.SerialNumber = this.txtOrderNo.Text;
            TransferModel.ValidTime = int.Parse(this.txtValidTime.Text);
            DB.SaveChanges();

            Argee(txtExplain.Text, loginid, this.RelationID, branchID);
            loadInfo();
            //LoadData();
            //PartyTaskHelper.TaskDoneByTaskId(this.TaskID, loginid);
            this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('审批完成！'); (function(){var aw=F.wnd.getActiveWindow();if(aw){aw.f_hide_postback();}})();", true);
        }

        protected void btnNotArgee_Click(object sender, EventArgs e)
        {
            loadInfo();
            string branchID = PartyTask.GetTaskToUser(this.TaskID);
            var loginid = this.CurrentUser.LoginID;

            TransferModel.SerialNumber = this.txtOrderNo.Text;
            DB.SaveChanges();

            NotArgee(this.txtExplain.Text, loginid, this.RelationID, branchID);
            //LoadData();
            //PartyTaskHelper.TaskDoneByTaskId(this.TaskID, loginid);
            this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('审批完成！');(function(){var aw=F.wnd.getActiveWindow();if(aw){aw.f_hide_postback();}})();", true);

        }

        public string GetMemberCost(int index)
        {
            if (string.IsNullOrEmpty(TransferModel.MemberCostTime))
            {
                return "";
            }
            string[] temp = TransferModel.MemberCostTime.Split('-');
            if (temp.Length != 2)
            {
                return "";
            }
            return temp[index];
        }

        public string GetPoliticsLineamentName(string value)
        {
            DropDownList list = new DropDownList();
            ControlBusiness.ControlBindDataDictionary(list, "ZHDJ.Member.PoliticsLineament");
            list.SelectedValue = value;
            return list.Items[list.SelectedIndex].Text.Replace("党员", "");
        }

        public void Argee(string explain, string loginId, string RelationID, string branchID)
        {
            string host = Request.Url.Host;
            PartyTaskHelper.TaskDone(RelationID, this.CurrentUser.LoginID);

            DataTable dt = PartyRelationshipTransfer.GetGridData(RelationID).Tables[0];
            if (dt.Rows.Count == 0)
            {
                return;
            }
            string lbExplain = Convert.ToString(dt.Rows[0]["Explain"]);
            string lbApplicant = Convert.ToString(dt.Rows[0]["UserName"]);
            string lbFormBranch = Convert.ToString(dt.Rows[0]["FromBranchName"]);
            string lbTageBranch = Convert.ToString(dt.Rows[0]["TageBranchName"]);
            string hdFromID = Convert.ToString(dt.Rows[0]["FormerBranchID"]);
            string hdTageID = Convert.ToString(dt.Rows[0]["TageBranchID"]);
            string hdLoginID = Convert.ToString(dt.Rows[0]["Applicant"]);

            PartyRelationshipProcesses pr = new PartyRelationshipProcesses();
            pr.ID = StringHelper.NewID;
            pr.ApplyID = RelationID;
            pr.Approver = loginId;
            pr.Explain = explain;
            pr.ApprovalResult = "同意";
            pr.CreateTime = DateTime.Now;

            DataTable dtstep = PartyRelationshipTransfer.GetCurrentStep(RelationID, branchID);
            if (dtstep.Rows.Count == 0)
                return;
            int stepCount = Convert.ToInt32(dtstep.Rows[0]["OrderNO"]);
            int sumOrder = Convert.ToInt32(dtstep.Rows[0]["SumOrder"]);

            if (sumOrder == stepCount)
            {

                //最后一步
                pr.StepInfo = (stepCount).ToString();
                pr.ApprovalResult = "同意-流程完成";
                DB.PartyRelationshiptblProcessess.Add(pr);
                DB.SaveChanges();

                //更新申请单记录
                PartyRelationshipTransfer rt = DB.PartyRelationshipTransfers.Find(RelationID);
                rt.Status = "同意转组织";
                //DB.PartyRelationshipTransfers.Add(rt);
                DB.SaveChanges();

                //更新成员组织ID
                PartyOrgMember org = DB.PartyOrgMembers.Find(rt.Applicant);
                string branchTemp = org.BranchID;
                org.BranchID = rt.TageBranchID;
                org.runSate = "0";
                if (rt.Type == 1) {
                    org.runSate = "2";
                }

                //DB.PartyOrgMembers.Add(org);
                DB.SaveChanges();

                //发送待办给申请人
                PartyTaskHelper.AddTaskToMember(RelationID, lbApplicant + "组织关系转移审核通过", SysEnum.TaskCategory.RelationshipTransfer,
                   this.CurrentUser.LoginID, new string[] { hdLoginID },
                   "../../../../App/PersonalCenter/Module/RelationshipTransfer/RelationshipTransferApproval.aspx?RelationID=" + RelationID + "&end=true");

                //增加到历史党员库
                //org.BranchID = branchTemp;
                AddToHistoryMember(org, lbExplain, branchTemp);
                //入党流程
                //RunPartyJoinApplycation(rt.Applicant, lbApplicant, hdTageID, branchTemp, this.CurrentUser.LoginID);

                //插入组织转接公示
                AddToPublicity(dt);

                //给申请人发送短信提醒
                string msgcontent = string.Format("{0}同志：你的组织关系转移申请已办理完毕，详情可登录山海天党建信息平台查看。", org.UserName);
                SMSHelper.CreateSmsSendRecord(org.MobileNo, msgcontent, "组织关系转移办结");
            }
            else
            {
                pr.StepInfo = (stepCount + 1).ToString();
                DB.PartyRelationshiptblProcessess.Add(pr);
                DB.SaveChanges();
            }

            //取下一步处理人
            if (stepCount < sumOrder)
            {
                DataTable dtlogin = PartyRelationshipTransfer.GetRelationshipTageBranch(RelationID, stepCount + 1);
                if (dtlogin.Rows.Count == 0)
                    return;
                //推送待办
                String[] tobranchid = new String[] { Convert.ToString(dtlogin.Rows[0]["TageBranchID"]) };

                //组织
                PartyTaskHelper.AddTaskToBranch(RelationID, lbApplicant + "组织关系转移申请", SysEnum.TaskCategory.RelationshipTransfer,
                    this.CurrentUser.LoginID, tobranchid,
                    "../../../../App/PersonalCenter/Module/RelationshipTransfer/RelationshipTransferApproval.aspx?RelationID=" + RelationID + "&ProcessID=" + pr.ID);

                //代办人短信提醒
                var targetbranchid = Convert.ToString(dtlogin.Rows[0]["TageBranchID"]);
                var allLoginID = DB.PartyOrgMembers.Where(o => o.BranchID == targetbranchid && o.IsPartyWorker == true).ToList();

                //string[] allLoginID = pjle.ToDoHandleUserID.Split(',');

                string msgcontent = "尊敬的{0}同志，现有一个{1}的组织关系转移申请需处理，请您登录山海天党建管理平台处理。";
                foreach (var item in allLoginID)
                {
                    SMSHelper.CreateSmsSendRecord(item.MobileNo, string.Format(msgcontent, item.UserName, dt.Rows[0]["UserName"]), "组织关系转移申请处理");
                }
            }
        }

        public string GetBranchName(object id)
        {
            var dd = ZHDJ.WebPage.ControlBusiness.GetBranchPickerText(id.ToString());
            if (dd == "")
                dd = id.ToString();
            return dd;
        }

        public void NotArgee(string explain, string loginId, string RelationID, string branchID)
        {
            string host = Request.Url.Host;
            PartyTaskHelper.TaskDone(RelationID, this.CurrentUser.LoginID);
            DataTable dtstep = PartyRelationshipTransfer.GetCurrentStep(RelationID, branchID);
            if (dtstep.Rows.Count == 0)
                return;
            int stepCount = Convert.ToInt32(dtstep.Rows[0]["OrderNO"]);
            int sumOrder = Convert.ToInt32(dtstep.Rows[0]["SumOrder"]);

            PartyRelationshipProcesses pr = new PartyRelationshipProcesses();
            pr.ID = StringHelper.NewID;
            pr.ApplyID = RelationID;
            pr.Approver = this.CurrentUser.LoginID;
            pr.Explain = explain;
            pr.ApprovalResult = "不同意";
            pr.CreateTime = DateTime.Now;
            pr.StepInfo = (stepCount - 1).ToString();
            DB.PartyRelationshiptblProcessess.Add(pr);
            DB.SaveChanges();

            //更新申请单记录
            PartyRelationshipTransfer rt = DB.PartyRelationshipTransfers.Find(RelationID);
            rt.Status = "不同意转组织";
            //DB.PartyRelationshipTransfers.Add(rt);
            DB.SaveChanges();

            //退回上一部
            if (stepCount == 1)
            {
                //发送待办给申请人
                PartyTaskHelper.AddTaskToMember(RelationID, "组织关系转移审核不通过", SysEnum.TaskCategory.PartyRepresentative,
                       this.CurrentUser.LoginID, new string[] { rt.Applicant },
                       "../../../../App/PersonalCenter/Module/RelationshipTransfer/RelationshipTransferApproval.aspx?RelationID=" + RelationID + "&end=true");
            }
            else
            {
                DataTable dt = PartyRelationshipTransfer.GetGridData(RelationID).Tables[0];
                if (dt.Rows.Count == 0)
                {
                    return;
                }
                var lbApplicant = Convert.ToString(dt.Rows[0]["UserName"]);

                DataTable dtlogin = PartyRelationshipTransfer.GetRelationshipTageBranch(RelationID, stepCount - 1);
                if (dtlogin.Rows.Count == 0)
                    return;
                //推送待办
                String[] tobranchid = new String[] { Convert.ToString(dtlogin.Rows[0]["TageBranchID"]) };

                //组织
                PartyTaskHelper.AddTaskToBranch(RelationID, lbApplicant + "组织关系转移申请", SysEnum.TaskCategory.RelationshipTransfer,
                    this.CurrentUser.LoginID, tobranchid,
                    "../../../../App/PersonalCenter/Module/RelationshipTransfer/RelationshipTransferApproval.aspx?RelationID=" + RelationID + "&ProcessID=" + pr.ID);
            }

        }


        /// <summary>
        /// //增加到历史党员库
        /// </summary>
        /// <param name="history"></param>
        /// <param name="runreason"></param>
        public void AddToHistoryMember(PartyOrgMember history, string runreason, string oldBranchID)
        {
            PartyOrgMemberHistory oModel = new PartyOrgMemberHistory();
            oModel.HistoryID = StringHelper.NewID;
            oModel.UserNo = history.UserNo;
            oModel.LoginID = history.LoginID;
            oModel.Address = history.Address;
            oModel.BeRegularDate = history.BeRegularDate;
            oModel.Birthday = history.Birthday;
            oModel.BranchID = oldBranchID;
            oModel.BranchRight = history.BranchRight;
            oModel.DemocraticAppraisal = history.DemocraticAppraisal;
            oModel.Educational = history.Educational;
            oModel.Email = history.Email;
            oModel.EmployeeStatus = history.EmployeeStatus;
            oModel.feitionNo = history.feitionNo;
            oModel.Gender = history.Gender;
            oModel.IdentityCard = history.IdentityCard;
            oModel.ImageUrl = history.ImageUrl;
            oModel.IsAgree = history.IsAgree;
            oModel.IsFirstLogin = history.IsFirstLogin;
            oModel.isHardParty = history.isHardParty;
            oModel.isPartyDeputy = history.isPartyDeputy;
            oModel.IsPartyWorker = history.IsPartyWorker;
            oModel.isVolunteer = history.isVolunteer;
            oModel.JoinPartyDate = history.JoinPartyDate;
            oModel.LoginID = history.LoginID;
            oModel.MobileNo = history.MobileNo;
            oModel.Nation = history.Nation;
            oModel.NativePlace = history.NativePlace;
            oModel.OrderNo = history.OrderNo;
            oModel.Password = history.Password;
            oModel.PoliticsLineament = history.PoliticsLineament;
            oModel.Post = history.Post;
            oModel.pwdOverTime = history.pwdOverTime;
            oModel.QQNumber = history.QQNumber;
            oModel.RewardsPunishment = history.RewardsPunishment;
            oModel.UserName = history.UserName;
            oModel.RunType = 2;
            oModel.Runreason = runreason;
            oModel.RunTime = DateTime.Now;

            DB.PartyOrgMemberHistorys.Add(oModel);
            DB.SaveChanges();
        }

        /// <summary>
        /// 入党流程处理 ，（如果用户正申请入党）
        /// </summary>
        /// <param name="backToStepID">指定步骤</param>
        /// <param name="applyBy">申请人</param>
        /// <param name="branchID">申请进入的组织(为空时组织不变）</param>
        public void RunPartyJoinApplycation(string applyBy, string username, string TobranchID, string oldBranchID, string handler)
        {
            var CurrentStepID = PartyTask.GetCurrentStepIDByLoginID(applyBy);
            var backtostep = "";
            if (CurrentStepID == ProcessUtil.JoinStep7
                || CurrentStepID == ProcessUtil.JoinStep8
                || CurrentStepID == ProcessUtil.JoinStep9)
            {
                //撤回到6
                backtostep = ProcessUtil.JoinStep6;
            }
            else if (CurrentStepID == ProcessUtil.JoinStep14
               || CurrentStepID == ProcessUtil.JoinStep13)
            {
                //撤回到11
                backtostep = ProcessUtil.JoinStep11;
            }
            else
            {
                backtostep = CurrentStepID;
            }
            if (string.IsNullOrEmpty(backtostep))
                return;
            var rs = PartyTask.BackToStep(backtostep, applyBy, TobranchID, handler);
            var relatiionid = StringHelper.NewID;
            //待办
            if (rs)
            {
                //通知申请人 短信
                try
                {
                    var mobile = PartyOrgMember.QueryMemberMobileNo(applyBy).Trim();
                    //if (mobile != "")
                    //{
                    //    PartySMSLibrary.SendMassage(new List<string>() { mobile }, string.Format("{0}你好，你的组织关系转移申请已审核通过。", username), "组织关系转移");
                    //}
                }
                catch (Exception ex)
                {
                    //SXT.Utility.ExceptionLogs.Write(ex);
                }

                //通知组织-前
                relatiionid = StringHelper.NewID;
                PartyTask.AddTask(relatiionid, username + "入党申请审核流程变更",
"组织转移申请", this.CurrentUser.LoginID,
new string[] { oldBranchID },
"../../../../../Admin/Project/JoinParty/Module/Audit/RelationshipTransfer.aspx?ApplyBy=" + applyBy + "&OldBranchID=" + oldBranchID + "&StepID=" + CurrentStepID + "&RelationID=" + relatiionid,
"Branch");

                //通知组织-后
                relatiionid = StringHelper.NewID;
                PartyTask.AddTask(relatiionid, username + "入党申请审核流程变更",
"组织转移申请", this.CurrentUser.LoginID,
new string[] { TobranchID },
"../../../../../Admin/Project/JoinParty/Module/Audit/RelationshipTransfer.aspx?ApplyBy=" + applyBy + "&OldBranchID=" + oldBranchID + "&StepID=" + CurrentStepID + "&RelationID=" + relatiionid,
"Branch");
            }
        }


        public void AddToPublicity(DataTable dttransfer)
        {
            var model = new PartyRelationnshipPublicity();
            model.ID = StringHelper.NewID;
            model.StandID = "";
            model.StepID = "";
            model.AppllicationID = Convert.ToString(dttransfer.Rows[0]["Id"]);
            model.LoginID = "";
            model.Category = "publicity";
            model.Title = Convert.ToString(dttransfer.Rows[0]["UserName"]) + "同志党组织关系已于" + DateTime.Now.ToLongDateString().ToString() + ",由"+
            Convert.ToString(dttransfer.Rows[0]["FromBranchName"]) + "成功转移到"+ Convert.ToString(dttransfer.Rows[0]["TageBranchName"]); ;
            model.CreateTime = DateTime.Now;
            model.NoticeTime = "";
            DB.PartyRelationnshipPublicitys.Add(model);
            DB.SaveChanges();
        }
    }
}